package com.transactional.manager.service

import com.transactional.manager.bean.mysql.User
import com.transactional.manager.bean.postgres.Order
import com.transactional.manager.bean.vo.IndexVo
import com.transactional.manager.repository.mysql.UserRepository
import com.transactional.manager.repository.postgres.OrderRepository
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Service
import org.springframework.transaction.annotation.Transactional
import java.time.LocalDateTime

@Service
class IndexService {

    @Autowired
    lateinit var userRepository: UserRepository

    @Autowired
    lateinit var orderRepository: OrderRepository

    @Transactional(rollbackFor = [Exception::class])
    fun index(indexVo: IndexVo) {
        val user = User(username = indexVo.username, email = indexVo.email)
        userRepository.save(user)

        val order = Order(userId = user.id!!, amount = indexVo.amount,
            orderTime = LocalDateTime.now(), status = "ORDERED", productName = indexVo.productName)
        orderRepository.save(order)

        // 测试多数据源事务回滚
        if (indexVo.testRollback == true) {
            throw RuntimeException("测试分布式事务回滚")
        }
    }

}